package jp.co.hcs.attendancemanagement.login.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jp.co.hcs.attendancemanagement.AMConstants;
import jp.co.hcs.attendancemanagement.login.actionform.LoginForm;
import jp.co.hcs.attendancemanagement.login.logic.LoginLogic;
import jp.co.hcs.attendancemanagement.login.logic.dto.LoginDto;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class LoginAction extends Action {

  private final static String SUCCESS = "success";
  private final static String FAILURE = "failure";

  /**
   * This is the action called from the Struts framework.
   * 
   * @param mapping The ActionMapping used to select this instance.
   * @param form The optional ActionForm bean for this request.
   * @param request The HTTP Request we are processing.
   * @param response The HTTP Response we are processing.
   * @throws java.lang.Exception
   * @return
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
      HttpServletResponse response) throws Exception {
    LoginForm loginForm = (LoginForm) form;
    LoginDto loginDto = new LoginDto();
    BeanUtils.copyProperties(loginDto, loginForm);

    LoginLogic login = new LoginLogic();
    String userId = login.authenticate(loginDto);

    if (userId != null) {
      request.getSession().setAttribute(AMConstants.USER_LOGGED_IN, userId);
      return mapping.findForward(SUCCESS);
    } else {
      ActionMessages errors = new ActionMessages();
      errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.login.failure"));
      saveErrors(request, errors);
      return mapping.findForward(FAILURE);
    }
  }

}
